//
//  ZwayEsp32WifiPrivate.h
//
//  Created by Alexander Polyakov on 11/10/24
//
//  Copyright (c) 2024 Trident IOT
//
//
#ifndef zway_esp32_wifi_private_h
#define zway_esp32_wifi_private_h

#include "ZPlatform.h"
#include "ZLogging.h"

#include "esp_err.h"
#include "esp_wifi.h"

#ifdef ZWAY_ESP32_DEBUG
#define ZWAY_ESP32_LOG_ERR(ZWAY, LEVEL, STR, ERR) zway_log_error(ZWAY, LEVEL, STR, ERR)
#define ZWAY_ESP32_LOG_ERR_EXT(LOGGER, SOURSE, LEVEL, STR, ERR) zlog_error(LOGGER, SOURSE, LEVEL, STR, ERR);
#define ZWAY_ESP32_LOG_PRINT_EXT(LOGGER, SOURSE, LEVEL, STR, ...) zlog_write(LOGGER, SOURSE, LEVEL, STR, __VA_ARGS__);
#else
#define ZWAY_ESP32_LOG_ERR(ZWAY, LEVEL, STR, ERR)
#define ZWAY_ESP32_LOG_ERR_EXT(LOGGER, SOURSE, LEVEL, STR, ERR)
#define ZWAY_ESP32_LOG_PRINT_EXT(LOGGER, SOURSE, LEVEL, STR, ...)
#endif // ZWAY_ESP32_DEBUG

#define ZWAY_ESP32_CURRENT_WIFI_CREDENTIALS_VERSION 0x00000100
#define ZWAY_ESP32_WIFI_CREDENTIAL_FILENAME "wifi_cred.bin"
#define ZWAY_ESP32_DEFAULT_AP_WIFI_PASS "12345678"

typedef struct _ZwayEsp32WifiCredentialsInfo_s
{
    ZWCHAR ssid[32];
    ZWCHAR psw[32];
} _ZwayEsp32WifiCredentialsInfo_t;

typedef struct _ZwayEsp32WifiCredentials_s
{
    ZWDWORD version;
    ZWWORD crc16;
    _ZwayEsp32WifiCredentialsInfo_t info;
} _ZwayEsp32WifiCredentials_t;

typedef struct _ZwayEsp32WifiCtx_s
{
    ZWLog logger;
    ZWCSTR source;
    esp_netif_t *s_example_sta_netif;
    esp_ip4_addr_t ip4;
    SemaphoreHandle_t s_semph_wait_wifi;
    size_t s_retry_num;
    bool inited;
} _ZwayEsp32WifiCtx_t;

ZWError _zway_esp32_save_wifi_credentials(ZWCSTR filename, _ZwayEsp32WifiCredentials_t *cred);
ZWError _zway_esp32_load_wifi_credentials(ZWCSTR filename, _ZwayEsp32WifiCredentials_t *cred);
ZWError _zway_esp32_wifi_connect(_ZwayEsp32WifiCtx_t **ctx, ZWLog logger, ZWCSTR source, ZWBOOL force_ap);

static inline ZWDWORD _zway_esp32_get_wifi_ip4(_ZwayEsp32WifiCtx_t *ctx)
{
    return ctx->ip4.addr;
};

typedef struct ZwayEsp32Hostname_s
{
    ZWCHAR data[16];
} ZwayEsp32Hostname_t;

ZWError _zway_esp32_get_hostname(ZwayEsp32Hostname_t *hostname);

#endif // zway_esp32_wifi_private_h
